#include <iostream>
#include <string>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>

class SocketClient {
public:
    SocketClient(const std::string& server_ip, int server_port)
        : server_ip_(server_ip), server_port_(server_port), sockfd_(-1) {}

    ~SocketClient()
    {
        if (sockfd_ != -1) 
        {
            close(sockfd_);
        }
    }

    bool connectToServer() 
    {
        sockfd_ = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd_ == -1) 
        {
            std::cerr << "Failed to create socket." << std::endl;
            return false;
        }

        sockaddr_in server_addr;
        memset(&server_addr, 0, sizeof(server_addr));
        server_addr.sin_family = AF_INET;
        server_addr.sin_port = htons(server_port_);

        if (inet_pton(AF_INET, server_ip_.c_str(), &server_addr.sin_addr) <= 0) 
        {
            std::cerr << "Invalid address/ Address not supported." << std::endl;
            close(sockfd_);
            return false;
        }

        if (connect(sockfd_, (struct sockaddr*) & server_addr, sizeof(server_addr)) < 0)
        {
            std::cerr << "Connection to server failed." << std::endl;
            close(sockfd_);
            return false;
        }

        std::cout << "Connected to server." << std::endl;
        return true;
    }

    bool sendMessage(const std::string& message)
    {
        if (send(sockfd_, message.c_str(), message.size(), 0) == -1) 
        {
            std::cerr << "Failed to send message." << std::endl;
            return false;
        }
        return true;
    }

    std::string receiveMessage()
    {
        char buffer[1024] = { 0 };
        ssize_t bytes_received = recv(sockfd_, buffer, sizeof(buffer), 0);
        if (bytes_received == -1) 
        {
            std::cerr << "Failed to receive message." << std::endl;
            return "";
        }
        return std::string(buffer, bytes_received);
    }

private:
    std::string server_ip_;
    int server_port_;
    int sockfd_;
};

int main() 
{
    SocketClient client("127.0.0.1", 8585);
    if (client.connectToServer())
    {
		while(1)
		{
			client.sendMessage("Temperature data: 25.4 C");
        	std::string response = client.receiveMessage();
        	std::cout << "Server response: " << response << std::endl;
			sleep(2000);
		}
	}
    return 0;
}
